import { payment as orderPayment } from "@/api/shopApi/order";
// import { payment as vipPayment } from "@/api/vip";
import { interpreter } from "@/api/request";
import { AIToken, Token } from "../cache";
import isWeChat from "../isWechat";
import Popup from "./popup.vue";
import Qrcode from "qrcode";
import toPayPage from "../toPayPage";
import { h, ref } from "vue";
import { wxpayment } from "@/api/vip";

function createPopup(code: string) {
  const payPopup = ref();
  const popup = h(Popup, {
    code,
    ref: payPopup
  });
  // render(popup, document.body);
  popup.component!.refs.payPopup!.open();
}

export default async function payment(
  orderId: string,
  redirect_url: string,
  success?: () => void
) {
  if (!Token.get() || !AIToken.get()) {
    uni.showModal({
      title: "温馨提示",
      content: "您还未登录，是否前往登录",
      success(res) {
        if (res.confirm) {
          uni.redirectTo({ url: `/pages/login/login` });
        }
      }
    });
    return;
  }
  // #ifdef MP-WEIXIN
  const [err, wxRes] = await interpreter(wxpayment(orderId));
  if (!err) {
    const params = JSON.parse(wxRes.json);
    // success?.();
    uni.requestPayment({
      ...params,
      success(res: any) {
        if (res.errMsg === "requestPayment:ok") {
          // 更新用户信息
          uni.showToast({
            title: "支付成功"
          });
          success?.();
        }
      }
    });
  } else {
    uni.showToast({
      title: "发起支付失败",
      icon: "none"
    });
  }
  // #endif
  // #ifdef H5
  const [err, res] = await interpreter(orderPayment(orderId));
  if (!err) {
    const url = toPayPage(res.url, {
      order_id: res.order_id,
      redirect_url
    });
    console.log("url", decodeURIComponent(url));
    if (!isWeChat()) {
      const res = await Qrcode.toDataURL(url, {
        correctLevel: "H"
      });
      if (typeof res === "string") {
        createPopup(res);
      } else {
        uni.showToast({
          title: "生成二维码失败",
          icon: "none"
        });
      }

      return;
    }
    window.location.href = url;
  } else {
    uni.showToast({
      title: "支付失败",
      icon: "none"
    });
  }
  // #endif
}
